package com.wangke.test.container;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangke
 * @version v1.0
 * @项目名称: study
 * @描述: 用reentrantLock实现同步容器
 * @创建时间: 2019/4/26
 * @update [序号][日期YYYY-MM-DD] [更改人姓名][变更描述]
 */
public class MyContainer2<T> {
    final  private  LinkedList<T> lists = new LinkedList<T>();
    final int MAX = 10;
    int count = 0;
    private Lock lock = new ReentrantLock();
    private Condition producer = lock.newCondition();
    private Condition consumer = lock.newCondition();

    public void put(T t){
        try{
            lock.lock();
            while (lists.size()==MAX){
                producer.await(); //当消费者线程们执行到这里的时候等待
            }
            lists.add(t);
            ++count;
            System.out.println("里面有个数："+count);
            consumer.signalAll(); //通知消费者线程进行消费
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }


    /**
     *
     * @return
     */
    public T get(){
        lock.lock();
        try {
            while (lists.size() == 0) {
                consumer.await();//当消费完了，提醒生产者开始生产
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        T t = null;

        t = lists.removeFirst();

        return t;
    }


    public static void main(String[] args) {

    }



}
